package com.sensor.Manager;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.code.CollectParam;
import com.code.CollectTask;
import com.code.CommandType;
import com.code.Encode;
import com.landmesure.communication.BaseManager;
import com.landmesure.communication.MonitorItemDecode;
import com.landmesure.communication.SendMessageService;
import com.landmesure.core.TestMessage;
import com.sensor.core.DeviceStatus;
import com.sensor.core.HandlerMessage;
import com.util.EncodeUtil;
import com.util.OkHttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.ContentValues.TAG;
import static com.code.DataType.CODE_ERROR;
import static com.code.DataType.CODE_HISTROYDATA;
import static com.code.DataType.CODE_OBJECTDATA;
import static com.code.DataType.CODE_PARAM;
import static com.code.DataType.CODE_STATUSDATA;
import static com.code.DataType.CODE_STATUS_TESTDATA;
import static com.code.DataType.CODE_SUCCESS;
import static com.code.DataType.CODE_SUCCESS_QUERYDATA;
import static com.code.DataType.CODE_SUCCESS_TEST;
import static com.code.DataType.CODE_TESTDATA;

public class WaterMonitorManager extends BaseManager {

    public List<String> cjkzqList = new ArrayList<>();
    public Map<String, JSONObject> cjkzqMap = new HashMap<>();
    private List<Map<String, String>> initDatasList = new ArrayList<>();
    public List<DeviceStatus> initDatas = new ArrayList<>();

    public WaterMonitorManager(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void processRcvMessage(String readMessage) {
        {
            Log.i(TAG, "来消息了: " + readMessage);
            appendMessage(readMessage, totalMessage);
            processScodeForDecode();
        }
    }

    @Override
    protected void switchMessage(String ms) throws Exception {

        int dataType = getDataType(ms);
        switch (dataType) {
            case CODE_TESTDATA:
                processTestMessage(ms);
                break;
            case CODE_STATUSDATA:
                break;
            case CODE_SUCCESS:
                break;
            case CODE_PARAM:
                break;
            case CODE_OBJECTDATA:
                break;
            case CODE_ERROR:
                break;
            case CODE_HISTROYDATA:
                break;
            case CODE_SUCCESS_QUERYDATA:
                break;
            case CODE_SUCCESS_TEST:
                break;
            case CODE_STATUS_TESTDATA:
                break;
            default:
                break;
        }
    }

    protected void processScodeForDecode() {
        String doneMessageStr = doneMessage.toString();
        String totalMessageStr = totalMessage.toString();
        int doneMessageLen = doneMessageStr.length();
        int totalMessageLen = totalMessageStr.length();
        if (doneMessageLen >= totalMessageLen) return;
        String newReadMessageStr = totalMessageStr.substring(doneMessageLen, totalMessageLen);
        String[] newReadMessageArr = newReadMessageStr.split(PROTOCOL07_TYPE);
        for (String str : newReadMessageArr) {
            String realDataStr = PROTOCOL_TYPE + str;
            int dataRealLen = realDataStr.length();
            if (dataRealLen > MIN_DATA_LEN) {
                int dataCorrectLen = Integer.parseInt(realDataStr.substring(4, 6), 16) * 2 + 32;
                if (dataRealLen == dataCorrectLen) {
                    appendMessage(realDataStr, doneMessage);
                    try {
                        switchMessage(realDataStr);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

        }

    }

    private void processTestMessage(String ms) throws ParseException {
        int ecode = Integer.parseInt(ms.substring(26, 30), 16);
        for (Map<String, String> map : initDatasList
        ) {
            if (map.get("对应ID")!=null&&Integer.parseInt(map.get("对应ID")) == ecode) {
                Log.i(TAG, "来数据了: " + map.get("对象角色"));

                switch (map.get("对象角色")) {
                    case "COD分析仪数据接口": {
                        List<TestMessage> testMessages = MonitorItemDecode.decodeMonitorItem(ms);
                        if (!hasMonitorItem(testMessages, "状态量")) {
                            sendTestMessage2Fragment(testMessages.get(1), HandlerMessage.WaterMonitor.READ_CCD);
                        }
                        break;
                    }
                    case "SS分析仪数据接口": {
                        List<TestMessage> testMessages = MonitorItemDecode.decodeMonitorItem(ms);
                        if (!hasMonitorItem(testMessages, "状态量")) {
                            sendTestMessage2Fragment(testMessages.get(1), HandlerMessage.WaterMonitor.READ_SS);
                        }
                        break;
                    }
                    case "总磷分析仪数据接口": {
                        List<TestMessage> testMessages = MonitorItemDecode.decodeMonitorItem(ms);
                        if (!hasMonitorItem(testMessages, "状态量")) {
                            sendTestMessage2Fragment(testMessages.get(1), HandlerMessage.WaterMonitor.READ_ZL);
                        }
                        break;
                    }
                    case "氨氮分析仪数据接口": {
                        List<TestMessage> testMessages = MonitorItemDecode.decodeMonitorItem(ms);
                        if (!hasMonitorItem(testMessages, "状态量")) {
                            sendTestMessage2Fragment(testMessages.get(1), HandlerMessage.WaterMonitor.READ_AD);
                        }
                        break;
                    }
                    default:{
                        List<TestMessage> testMessages = MonitorItemDecode.decodeMonitorItem(ms);
                        if (hasMonitorItem(testMessages, "状态量")) {
                            sendTestMessage2Fragment(testMessages.get(1), HandlerMessage.WaterMonitor.READ_STATUS);
                        }
                    }
                }
            }
        }

    }

    public void serInitDatas(final ArrayAdapter<String> adapter, final Spinner cjkzqSpinner) {
        Map<String, Object> map = new HashMap<>();
        map.put("pcode", "79");
        map.put("mname", "LCU");
        map.put("tname", "四要素水质采集控制器");

        String url = "http://center.xaland.com.cn:8086/landsvr2012/entityDao/loadEntitiesByMetaAndTypeName.action";
        try {
            OkHttpUtil okHttpUtil = OkHttpUtil.getInstance();
            okHttpUtil.sendMap(url, map, new OkHttpUtil.Fun4() {
                @Override
                public void onResponse(JSONObject jsonObject) throws JSONException {
                    JSONArray contents = jsonObject.getJSONArray("content");
                    cjkzqList.clear();
                    cjkzqMap.clear();
                    for (int i = 0; i < contents.length(); i++) {
                        JSONObject content = (JSONObject) contents.get(i);
                        cjkzqList.add(String.valueOf(content.get("ename")));
                        cjkzqMap.put(String.valueOf(content.get("ename")), content);
                    }
                    cjkzqSpinner.setAdapter(adapter);
                    Log.i(TAG, "yuanonResponse: " + jsonObject);
                }

                @Override
                public void onFailure() {
                    Message msg = new Message();
                    msg.what = HandlerMessage.WaterMonitor.GET_CJKZQ_ERROR;
                    handler.sendMessage(msg);
                    Log.i(TAG, "yuanonResponse: 请求失败");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void serInitDatas(Long eid) {
        {
            Map<String, Object> map = new HashMap<>();
            map.put("pcode", "79");
            map.put("eid", eid);

            String url = "http://center.xaland.com.cn:8086/landsvr2012/operateDao/loadWaterMonitorDatas.action";
            try {
                OkHttpUtil okHttpUtil = OkHttpUtil.getInstance();
                okHttpUtil.sendMap(url, map, new OkHttpUtil.Fun4() {
                    @Override
                    public void onResponse(JSONObject jsonObject) throws JSONException {
                        JSONArray contents = jsonObject.getJSONArray("content");
                        initDatasList = com.alibaba.fastjson.JSONArray.parseObject(contents.toString(), List.class);
                        initDatas.clear();
                        for (Map m:initDatasList
                             ) {
                            if (!String.valueOf(m.get("tname")).equals("设备状态"))
                                continue;
                            DeviceStatus deviceStatus=new DeviceStatus();
                            deviceStatus.setEcode(Integer.parseInt(String.valueOf(m.get("ecode"))));
                            deviceStatus.setRole(String.valueOf(m.get("对应角色")));
                            deviceStatus.setEid(Integer.parseInt(String.valueOf(m.get("eid"))));
                            deviceStatus.setId(Integer.parseInt(String.valueOf(m.get("对应ID")==null?0:m.get("对应ID"))));
                            deviceStatus.setMname(String.valueOf(m.get("mname")));
                            deviceStatus.setName(String.valueOf(m.get("ename")));
                            deviceStatus.setTname(String.valueOf(m.get("tname")));
                            initDatas.add(deviceStatus);
                        }
                        Message msg = new Message();
                        msg.what = HandlerMessage.WaterMonitor.GET_INIT_DATAS_SUCCESS;
                        handler.sendMessage(msg);
                        Log.i(TAG, "yuanonResponse: " + jsonObject);
                    }

                    @Override
                    public void onFailure() {
                        Message msg = new Message();
                        msg.what = HandlerMessage.WaterMonitor.GET_CJKZQ_ERROR;
                        handler.sendMessage(msg);
                        Log.i(TAG, "yuanonResponse: 请求失败");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendCommand(int ecode, String status) {
        SendMessageService sendMessageService = new SendMessageService();
        String message = EncodeUtil.combineMessageForControl(0, "0006", ecode, status);
        try {
            sendMessageService.sendMessage(null, HandlerMessage.WaterMonitor.WATER_MONITER, null, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public Integer getEcodeByRole(String s) {
        for (DeviceStatus deviceStatus: initDatas) {
            if (deviceStatus.getRole().equals(s)) {
                return deviceStatus.getEcode();
            }
        }
        return null;
    }

    public void switchControl(int ecode,String value){
        Encode encode = new Encode();
		CollectTask collectTask = new CollectTask();
		collectTask.setDtype(CommandType.COMMAND_SET);
		collectTask.setEcode(ecode);
		collectTask.setProject(0);
		collectTask.setSourceGroup(1);
		collectTask.setSourceStation(1);
		collectTask.setMcode(25);
		collectTask.setTcode(8);
		collectTask.setTargetGroup(63);
		collectTask.setTargetStation(1023);
		List<CollectParam> collectParams = new ArrayList<>();
        CollectParam collectParam1 = new CollectParam();
        collectParam1.setPcode(1);
        collectParam1.setPvalue("25");
        collectParams.add(collectParam1);
        CollectParam collectParam2 = new CollectParam();
        collectParam2.setPcode(2);
        collectParam2.setPvalue("8");
        collectParams.add(collectParam2);
		CollectParam collectParam = new CollectParam();
		collectParam.setPcode(18);
		collectParam.setPvalue(value);
		collectParams.add(collectParam);
		collectTask.setCollectParams(collectParams);
		encode.encode(collectTask);
        SendMessageService sendMessageService = new SendMessageService();
        try {
            sendMessageService.sendMessage(null, HandlerMessage.WaterMonitor.WATER_MONITER, null, collectTask.getScode());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
